#ifndef XG_DB_SQLITECONNECTPOOL_CPP
#define XG_DB_SQLITECONNECTPOOL_CPP
//////////////////////////////////////////////////////////////
#include "../DBConnectPool.h"
#include "../SQLiteConnect.h"

#ifndef XG_SQLITE_BACKUP_TIMEOUT
#define XG_SQLITE_BACKUP_TIMEOUT	300
#endif

class SQLiteConnectPool : public DBConnectPool
{
protected:
	time_t ctime;

public:
	SQLiteConnectPool()
	{
		SQLiteConnect::Setup();

		ctime = time(NULL) - XG_SQLITE_BACKUP_TIMEOUT + stdx::random(3, 8);
	}

protected:
	DBConnect* createConnect()
	{
		string name = cfg.name;
		time_t now = time(NULL);
		SQLiteConnect* conn = new SQLiteConnect();

		if (ctime + XG_SQLITE_BACKUP_TIMEOUT < now)
		{
			ctime = now;

			if (path::size(name) <= XG_MEMFILE_MAXSZ)
			{
				static Mutex mtx;

				mtx.lock();

				if (SQLiteConnect::Check(name))
				{
					LogTrace(eIMP, "check sqlite[%s] success", name.c_str());

					if (SQLiteConnect::Backup(name))
					{
						LogTrace(eIMP, "backup sqlite[%s] success", name.c_str());
					}
					else
					{
						LogTrace(eIMP, "backup sqlite[%s] failed", name.c_str());
					}
				}
				else
				{
					LogTrace(eIMP, "check sqlite[%s] failed", name.c_str());

					if (SQLiteConnect::Modify(name))
					{
						LogTrace(eIMP, "modify sqlite[%s] success", name.c_str());
					}
					else
					{
						LogTrace(eERR, "modify sqlite[%s] failed", name.c_str());

						if (SQLiteConnect::Restore(name))
						{
							LogTrace(eIMP, "restore sqlite[%s] success", name.c_str());
						}
						else
						{
							LogTrace(eIMP, "restore sqlite[%s] failed", name.c_str());
						}
					}
				}

				mtx.unlock();
			}
		}

		if (conn->connect(name)) return conn;

		delete conn;

		return NULL;
	}
};

DEFINE_DBCONNECTPOOL_EXPORT_FUNC(SQLiteConnectPool)

//////////////////////////////////////////////////////////////
#endif